import { request, history } from 'umi';
import { message } from 'antd';

const MESSAGE_ERROR_KEY = 'global_key';
const MESSAGE_ERROR_DURATION = 2;

export const post = async (api, params = {}) => {
  try {
    const { response, data } = await request($HOST + api, {
      method: 'post',
      params: {},
      data: params,
      getResponse: true,
      requestType: 'json', // 使用 json 格式传递参数，可能需要后台支持跨域
      errorHandler(error) {
        throw error;
      },
    });
    // 服务异常了，报错
    if (response.status < 200 || response.status >= 400) {
      message.error({
        content: `服务开小差了，请稍后重试：${response.status}`,
        key: MESSAGE_ERROR_KEY,
        duration: MESSAGE_ERROR_DURATION,
      });
      return Promise.reject();
    }
    // 登陆失效了
    if (data.code === '999') {
      history.replace('/login');
      return Promise.reject();
    }
    return data;
  } catch (error) {
    console.error('request error: ', error);
    // 服务异常时，跳转到500页面，登陆接口除外
    if (api !== '/api/login') {
      history.push('/500');
    }
  }
};
